<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";
import ScreenTable from "@/components/ScreenTable/index.vue";
import { ITableData, IQueryParams, ITableListItem } from "./data";
import { IResponseData } from "@/@types/utils.request";
import { queryList, update, save, removeData, queryRoomList } from "./service";
import { ElMessage } from "element-plus";
import { ElMessageBox } from "element-plus";
import { ResultCodeEnum } from "@/enums/utils.request.enum";
import { useUserStore } from "@/store/user";
/* ====================== 表格 - 获取数据 S ============== */
// 表格 - 列表 - 初始化数据

const tableData = reactive<ITableData>({
	loading: false,
	list: [],
	pagination: {
		total: 0,
		current: 1,
		pageSize: 20,
		sizeChange: () => {},
		onChange: () => {},
	},
});

const searchKey = reactive<IQueryParams>({
	issueDescription: "",
	status:-1,
	ownersId: -1,
});

const userStore = useUserStore();
// 表格 - index
const tableIndexMethod = (index: number) => {
	return index + (tableData.pagination.current - 1) * tableData.pagination.pageSize + 1;
};

const getList = async (key: IQueryParams): Promise<void> => {
	tableData.loading = true;
	if (userStore.roles.includes("owners")) {
		key.ownersId = userStore.id;
	} else {
		key.ownersId = -1;
	}
	try {
		const response: IResponseData<any> = await queryList({
			pageSize: tableData.pagination.pageSize,
			pageNum: tableData.pagination.current,
			data: key,
		});
		const { data, total } = response;
		tableData.list = data || [];
		tableData.pagination = {
			total: Number(total) || 0,
			current: tableData.pagination.current,
			pageSize: tableData.pagination.pageSize,
			sizeChange: (size) => {
				tableData.pagination.current = size;
				getList(key);
			},
			onChange: (size) => {
				tableData.pagination.current = size;
				getList(key);
			},
		};
	} catch (error: any) {
		console.log(error);
	}
	tableData.loading = false;
};
onMounted(() => {
	getList(searchKey);
	if (userStore.roles.includes("owners")) {
		getRoomList();
	}
});

const dialogUpdateVisible = ref(false);
const dialogAddVisible = ref(false);

const saveData = reactive<ITableListItem>({
	buildingName: "",
	roomNumber: "",
	issueDescription: "",
	type: "",
	status: 0,
	submitTime: "",
});
const updateData = reactive<ITableListItem>({
	maintenanceId: -1,
	buildingName: "",
	roomNumber: "",
	issueDescription: "",
	type: "",
	status: 0,
	submitTime: "",
});

const saveSub = async (data?: ITableListItem) => {
	if (!data) {
		ElMessage.error("信息错误");
		return;
	}
	const response: IResponseData<ITableListItem> = await save(data);
	const { code } = response;
	if (code == ResultCodeEnum.SUCCESS) {
		ElMessage.success("保存成功");
		dialogAddVisible.value = false;
		getList(searchKey);
	} else {
		ElMessage.error(response.message);
	}
};

const showDetail = (data: ITableListItem) => {
	updateData.maintenanceId = data.maintenanceId;
	updateData.buildingName = data.buildingName;
	updateData.roomNumber = data.roomNumber;
	updateData.issueDescription = data.issueDescription;
	updateData.type = data.type;
	updateData.status = data.status;
	updateData.submitTime = data.submitTime;
	dialogUpdateVisible.value = true;
};
const updateSub = async (data?: ITableListItem) => {
	if (!data) {
		ElMessage.error("信息错误");
		return;
	}
	const response: IResponseData<ITableListItem> = await update(data);
	const { code } = response;
	if (code == ResultCodeEnum.SUCCESS) {
		ElMessage.success("保存成功");
		dialogUpdateVisible.value = false;
		getList(searchKey);
	} else {
		ElMessage.error(response.message);
	}
};
// Fengcc
// 弹窗
const removeUser = async (id: number) => {
  const row = tableData.list.find((item) => item.maintenanceId === id);
  if (row && row.status !== 0) {
    ElMessage.error("只有未处理的报修才能撤销！");
    return;
  }

  ElMessageBox.confirm('确认撤销吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
  .then(async () => {
    const response: IResponseData<ITableListItem> = await removeData(id);
    const { code } = response;
    if (code == ResultCodeEnum.SUCCESS) {
      ElMessage.success("撤销成功");
      getList(searchKey);
    } else {
      ElMessage.error(response.message);
    }
  })
  .catch(() => {
    ElMessage.info('已取消撤销');
  });
};




const roleFormat = (row: any) => {
	// 取小数点后三位
	if (row.status == 0) {
		return "未处理";
	}
	if (row.status == 1) {
		return "已处理";
	}
	return "位置状态";
};
const searchAction = () => {
	getList(searchKey);
};

// 查询当前用户的所有的房间号
const roomList = ref([]);
const getRoomList = async (): Promise<void> => {
	try {
		const response: IResponseData<any> = await queryRoomList({
			pageSize: 100,
			pageNum: 1,
			data: {
				ownersId: userStore.id,
			},
		});
		const { data } = response;
		roomList.value = data || [];
	} catch (error: any) {}
};
</script>
<template>
  <ScreenTable row-key="id" :data="tableData.list" :loading="tableData.loading" :pagination="tableData.pagination">

    <template #header>
      <div class="header-box">
        <div class="header-box__left">
          <el-input placeholder="请输入问题描述" v-model="searchKey.issueDescription" style="width: 200px;" />
		  <el-select placeholder="请选择状态" v-model="searchKey.status" style="width: 200px;margin-left: 10px;">
		  			  <el-option label="全部" :value="-1" />
		  			  <el-option label="未处理" :value="0" />
		  			  <el-option label="已处理" :value="1" />
		  </el-select>
          <el-button type="primary" @click="searchAction">搜索</el-button>
        </div>
        <el-button v-if="userStore.roles.includes('owners','employees')" type="primary" @click="dialogAddVisible = true">新增</el-button>
      </div>
    </template>

    <el-table-column fixed label="序号" type="index" :index="tableIndexMethod" width="80"> </el-table-column>
    <el-table-column label="楼宇" prop="buildingName" width="150"> </el-table-column>
    <el-table-column label="门牌号" prop="roomNumber" width="150"> </el-table-column>
    <el-table-column label="报修类型" prop="type" width="150"> </el-table-column>
    <el-table-column label="问题描述" prop="issueDescription"> </el-table-column>
    <el-table-column label="状态" prop="status" width="150" :formatter="roleFormat"> </el-table-column>
    <el-table-column label="时间" prop="submitTime" width="200"> </el-table-column>
    <el-table-column v-if="userStore.roles.includes('owners')" label="操作" prop="action" width="150" fixed="right">
      <template #default="scop">
        <el-button type="primary" link @click="showDetail(scop.row)">修改</el-button>
        <el-button type="danger" link @click="removeUser(scop.row.maintenanceId)">撤销</el-button>
      </template>
    </el-table-column>
    <el-table-column v-if="userStore.roles.includes('employees')" label="操作" prop="action" width="150" fixed="right">
      <template #default="scop">
        <el-button type="primary" link @click="showDetail(scop.row)">解决回复</el-button>
		<el-button type="danger" link @click="removeUser(scop.row.maintenanceId)">撤销</el-button>
      </template>
    </el-table-column> 
  </ScreenTable>

  <!-- 修改 -->
  <el-dialog v-model="dialogUpdateVisible" top="20vh" title="修改信息">
    <el-form :model="updateData" label-width="auto" style="max-width: 600px">
      <el-form-item v-if="userStore.roles.includes('owners')" label="报修ID" style="display: none;">
        <el-input v-model="updateData.maintenanceId" />
      </el-form-item>
      <el-form-item v-if="userStore.roles.includes('owners')" label="报修类型">
        <el-input v-model="updateData.type" />
      </el-form-item>
      <el-form-item v-if="userStore.roles.includes('owners')" label="问题描述">
        <el-input type="textarea" maxlength="500" show-word-limit v-model="updateData.issueDescription" />
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="updateData.status" placeholder="请选择">
          <el-option label="未处理" v-if="userStore.roles.includes('employees')" :value="0" />
          <el-option v-if="userStore.roles.includes('employees')" label="已处理" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item v-if="userStore.roles.includes('owners')" label="时间">
        <el-date-picker v-model="updateData.submitTime" type="datetime" placeholder="Pick a Date" format="YYYY-MM-DD hh:mm:ss" value-format="YYYY-MM-DD hh:mm:ss" />
      </el-form-item>
      <el-button type="primary" @click="updateSub(updateData)">提交</el-button>
    </el-form>
  </el-dialog>

  <!-- 添加 -->
  <el-dialog v-model="dialogAddVisible" top="20vh" title="发布公告">
    <el-form :model="saveData" label-width="auto" style="max-width: 600px">
      <el-form-item label="报修ID" style="display: none;">
        <el-input v-model="saveData.maintenanceId" />
      </el-form-item>
      <el-form-item label="房间ID">
        <!-- <el-input v-model="saveData.roomsId" /> -->
        <el-select v-model="saveData.roomsId" placeholder="请选择">
          <el-option v-for="room in roomList" :key="room.roomId" :label="room.roomId" :value="room.roomId" />
        </el-select>
      </el-form-item>
      <el-form-item label="报修类型">
        <el-input v-model="saveData.type" />
      </el-form-item>
      <el-form-item label="问题描述">
        <el-input type="textarea" maxlength="500" show-word-limit v-model="saveData.issueDescription" />
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="saveData.status" placeholder="请选择" disabled>
          <el-option label="未处理" :value="0" />
          <el-option label="已处理" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="时间">
        <el-date-picker v-model="saveData.submitTime" type="datetime" placeholder="Pick a Date" format="YYYY-MM-DD hh:mm:ss" value-format="YYYY-MM-DD hh:mm:ss" />
      </el-form-item>
      <el-button type="primary" @click="saveSub(saveData)">提交</el-button>
    </el-form>
  </el-dialog>
</template>
